package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    /**
     * 图片上传
     * @param file
     */
    @Override
    public String fileUpload(MultipartFile file) {

        try {
            //todo 创建存储空间 下发虚拟机中包含gmall存储空间 切记保证该存储空间 访问权限设置Public
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
            }
            //1.构建新上传文件 文件对象标识 UUID+时间戳构成  /a/a.png
            //1.1 获取文件后缀
            String extName = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            //1.2 封装上传后文件名称
            String fileName = DateUtil.formatDate(new Date()) + "/" +
                    UUID.randomUUID().toString()
                            .replaceAll("-", "") + "." + extName;


            //2.调用Minioclient对象方法完成文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );

            //3.拼接上传后文件地址即可
            return endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}